//
//  ZBLinkman.m
//  BaseRACDemo
//
//  Created by Angel_Yan on 2018/3/27.
//  Copyright © 2018年 庄波. All rights reserved.
//

#import "ZBLinkman.h"
#import <AddressBook/AddressBook.h>
#import <Contacts/Contacts.h>

@interface ZBLinkman ()
@property (strong ,readwrite, nonatomic) NSArray<ZBLinkmanItem *> *arrLinkman;
@end


@implementation ZBLinkman

- (instancetype)init
{
    self = [super init];
    if (self) {
        CGFloat currentVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
        if (currentVersion < 9.0) {
            self.arrLinkman = [self allContactPerson];
        } else {
            self.arrLinkman = [self allContactPerson_IOS_9];
        }
    }
    return self;
}


/**
 *  通讯录权限
 *
 *  @param block block description
 */
- (void)CheckAddressBookAuthorization:(void (^)(bool isAuthorized))block;
{
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
    ABAuthorizationStatus authStatus = ABAddressBookGetAuthorizationStatus();
    if (authStatus != kABAuthorizationStatusAuthorized)
    {
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error){
            dispatch_async(dispatch_get_main_queue(), ^{
                if (error) {
                    NSLog(@"Error: %@", (__bridge NSError *)error);
                } else if (!granted) {
                    block(NO);
                } else {
                    block(YES);}
            });
        });
    } else {
        block(YES);
    }
}


/**
 *  9.0 已下读取通讯录
 *
 *  @return return value description
 */
- (NSArray *)allContactPerson;
{
    //声明一个通讯簿的引用
    ABAddressBookRef addBook = nil;
    //创建通讯簿的引用
    addBook = ABAddressBookCreateWithOptions(NULL, NULL);
    NSMutableArray * personArray = [[NSMutableArray alloc] init];
    //获取所有联系人的数组
    CFArrayRef allLinkPeople = ABAddressBookCopyArrayOfAllPeople(addBook);
    //获取联系人总数
    CFIndex number = ABAddressBookGetPersonCount(addBook);
    //进行遍历
    for (NSInteger i=0; i<number; i++) {
        //获取联系人对象的引用
        ABRecordRef  people = CFArrayGetValueAtIndex(allLinkPeople, i);
        //获取当前联系人名字
        NSString * firstName = (__bridge NSString *)(ABRecordCopyValue(people, kABPersonFirstNameProperty));
        //获取当前联系人姓氏
        NSString * lastName  = (__bridge NSString *)(ABRecordCopyValue(people, kABPersonLastNameProperty));
        //获取当前联系人的移动电话
        NSString * mobileNumber;
        NSString * name;
        NSData *imageData = (__bridge NSData *)ABPersonCopyImageData(people);
        //取名字
        if (lastName != nil && firstName != nil) {
            name = [NSString stringWithFormat:@"%@%@",lastName,firstName];
        } else if (firstName != nil) {
            name = firstName;
        } else if (lastName != nil) {
            name = lastName;
        }
        //获取当前联系人的电话 数组
        ABMultiValueRef phones = ABRecordCopyValue(people, kABPersonPhoneProperty);
        for (NSInteger j = 0; j< ABMultiValueGetCount(phones); j++) {
            NSString * number = (__bridge NSString *)(ABMultiValueCopyValueAtIndex(phones, j));
            //去掉号码分隔符
            NSRegularExpression * regular = [NSRegularExpression regularExpressionWithPattern:@"[( )-]" options:0 error:NULL];
            number = [regular stringByReplacingMatchesInString:number options:0 range:NSMakeRange(0, [number length]) withTemplate:@""];
            if ([number hasPrefix:@"+86"]) {
                number = [number substringFromIndex:3];
            }
            if ([number isMobileNumber]) {
                ///< 只要11位手机号
                mobileNumber = number;
                ZBLinkmanItem *item = [[ZBLinkmanItem alloc] init];
                item.dataPortrait = imageData;
                item.strPhone = mobileNumber;
                item.strNickName = name;
                [personArray addObject:item];
            }
        }
        CFRelease(phones);
        
//        if (personArray.count == 10) {
//            break;
//        }
    }
    CFRelease(addBook);
    return personArray;
}
/**
 *  ios 9 以上 读取通讯录
 *
 *  @return return value description
 */
- (NSArray *)allContactPerson_IOS_9;
{
    //初始化一个存取联系人的上下文桥梁
    CNContactStore * store = [[CNContactStore alloc] init];
    //设置提取联系人的哪些数据
    CNContactFetchRequest * request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[CNContactGivenNameKey,CNContactFamilyNameKey,CNContactPhoneNumbersKey,CNContactImageDataKey]];
    NSMutableArray * personArray = [[NSMutableArray alloc] init];
    //枚举遍历所有联系人的contact
    [store enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        //获取联系人姓名
        NSString * name = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];
        NSString * mobileNumber;
        NSData *imageData = contact.imageData;
        //遍历联系人所有号码
        for (CNLabeledValue * value in contact.phoneNumbers) {
            //是否是手机号
            CNPhoneNumber * phoneNumber = value.value;
            NSRegularExpression * regular = [NSRegularExpression regularExpressionWithPattern:@"[( )-]" options:0 error:NULL];
            NSString * number = [regular stringByReplacingMatchesInString:phoneNumber.stringValue options:0 range:NSMakeRange(0, [phoneNumber.stringValue length]) withTemplate:@""];
            
            if ([number hasPrefix:@"+86"]) {
                number = [number substringFromIndex:3];
            }
            if ([number isMobileNumber]) {
                ///< 只要11位手机号
                mobileNumber = number;
                ZBLinkmanItem *item = [[ZBLinkmanItem alloc] init];
                item.dataPortrait = imageData;
                item.strPhone = mobileNumber;
                item.strNickName = name;
                [personArray addObject:item];
                break;
            }
        }
        
//        if (personArray.count == 10) {
//            *stop = YES;;
//        }
    }];
    return personArray;
}
@end



@implementation ZBLinkmanItem

@end


